#!user/bin/python3
# -*- coding:UTF-8 -*-

################################################################################
#
# Copyright (c) 2020 openEuler.org, Inc. All Rights Reserved
#
################################################################################
"""
Handle mindspore tasks

Authors: zhangjianjun
Date:    05/08/2021 11:01 AM
"""

from dbConnecttion.MysqlConn import Mysql
import pymysql
from common import files
from common import times
from downloadtask import downloadfiletask
from tabletask import common


def download_mindspore_yaml():
    """
    Download the yaml file of mindspore on gitee
    return file_name
    """
    file_path = "./mindspore_yaml/"
    mk_ok = files.mkdirs(file_path, 1)
    file_name = file_path + 'mindspore_yaml.yaml'
    if mk_ok:
        # download the yaml file
        file_url = 'https://gitee.com/mindspore/community/raw/' \
                   'master/security/config/Third_Party_Open_Source_Software_List.yaml'
        downloadfiletask.download_yaml(file_name, file_url)
        # pass
    return file_name


def add_package_id(pk_id):
    """
    add index
    """
    packg_id = 10000000
    if pk_id > 0:
        packg_id = pk_id + 1
    return packg_id


def select_openeuler_yaml_data(mysql):
    """
    Query data
    """
    sql = "SELECT package_id, git_id,package_name,version FROM cve_git_open_euler " \
          "WHERE package_id >= %s"
    val = (10000000,)
    packages_data = mysql.getMany(sql, val)
    if packages_data and len(packages_data) > 0 and len(packages_data[0]) > 0:
        return packages_data
    else:
        return None


def delete_yaml_openeuler_data(mysql, git_id):
    """
    delete origin data
    """
    delete_sql = "delete from cve_git_open_euler where git_id = %s"
    val = (git_id,)
    mysql.delete(delete_sql, val)
    mysql.dispose()


def delete_yaml_openeuler_detail_data(mysql, git_id):
    """
    delete origin data
    """
    delete_sql = "delete from cve_git_package_info where git_id = %s"
    val = (git_id,)
    mysql.delete(delete_sql, val)
    mysql.dispose()


def insert_yaml_data(package_id, yaml_key, yaml_value, mysql):
    """
    insert data
    """
    insert_sql = "insert into cve_git_open_euler(package_id,package_name," \
                 "version,origin_url,create_time,update_time,cpe_packname,status) " \
                 "values(%s,%s,%s,%s,%s,%s,%s,%s)"
    val = (package_id, yaml_key, yaml_value["version"],
           yaml_value["url"], times.get_current_time(),
           times.get_current_time(), yaml_value["cpeName"], 1)
    last_id = mysql.insertOne(insert_sql, val)
    return last_id


def insert_yaml_detail_data(pg_detail_id, yaml_key, yaml_value, mysql):
    """
    insert data details
    """
    insert_sql = "insert into cve_git_package_info(git_id,package_name," \
                 "version,origin_url,create_time,update_time,decription,status) " \
                 "values(%s,%s,%s,%s,%s,%s,%s,%s)"
    val = (pg_detail_id, yaml_key, yaml_value["version"],
           yaml_value["url"], times.get_current_time(),
           times.get_current_time(), "", 0)
    last_id = mysql.insertOne(insert_sql, val)
    return last_id


def update_yaml_data(package_id, yaml_key, yaml_value, mysql):
    """
    update data
    """
    update_sql = "update cve_git_open_euler set origin_url = %s,update_time = %s, " \
                 "cpe_packname = %s,status=%s where package_id = %s " \
                 "and package_name =%s and version = %s"
    val = (yaml_value["url"], times.get_current_time(), yaml_value["cpeName"],
           1, package_id, yaml_key, yaml_value["version"])
    mysql.update(update_sql, val)


def update_yaml_detail_data(pg_detail_id, yaml_key, yaml_value, mysql):
    """
    Update data details
    """
    update_sql = "update cve_git_package_info set package_name = %s,version = %s, " \
                 "origin_url = %s, update_time = %s,status=%s where git_id = %s"
    val = (yaml_key, yaml_value["version"], yaml_value["url"],
           times.get_current_time(), 0, pg_detail_id)
    mysql.update(update_sql, val)


def update_yaml_origin_data(pg_origin_id, yaml_value, mysql):
    """
    Update origin data
    """
    update_sql = "update cve_mind_spore_yaml set origin_url = %s,status = %s, " \
                 "cpe_name = %s, update_time = %s, mark_bit = %s where id = %s"
    val = (yaml_value["url"], 1, yaml_value["cpeName"],
           times.get_current_time(), 1, pg_origin_id)
    mysql.update(update_sql, val)
    mysql.dispose()


def insert_yaml_origin_data(yaml_key, yaml_value, mysql, repo_key):
    """
    insert origin data
    """
    insert_sql = "insert into cve_mind_spore_yaml(package_name," \
                 "version,origin_url, status, cpe_name,create_time,update_time, mark_bit, repo_name) " \
                 "values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    val = (yaml_key, yaml_value["version"],
           yaml_value["url"], 1, yaml_value["cpeName"], times.get_current_time(),
           times.get_current_time(), 1, repo_key)
    last_id = mysql.insertOne(insert_sql, val)
    mysql.dispose()
    return last_id


def select_yaml_data(yaml_key, yaml_value, mysql):
    """
    Query data
    """
    sql = "SELECT package_id, git_id FROM cve_git_open_euler " \
          "WHERE package_name = %s " \
          "and version = %s order by package_id desc"
    val = (yaml_key, yaml_value["version"])
    packages_data = mysql.getMany(sql, val)
    if packages_data and len(packages_data) > 0 and len(packages_data[0]) > 0:
        return packages_data
    else:
        return None


def update_yaml_origin_mark(mysql):
    """
    Update origin data
    """
    update_sql = "update cve_mind_spore_yaml set mark_bit = 2 where mark_bit = 1"
    mysql.update(update_sql)
    mysql.dispose()


def delete_yaml_origin_mark(mysql):
    """
    delete origin data
    """
    delete_sql = "delete from cve_mind_spore_yaml where mark_bit = 2"
    mysql.delete(delete_sql)
    mysql.dispose()


def select_yaml_origin_data(package_name, version, mysql, repo_key):
    """
    Query origin data
    """
    sql = "SELECT id FROM cve_mind_spore_yaml WHERE package_name = %s " \
          "and version = %s and repo_name = %s"
    val = (package_name, version, repo_key)
    packages_data = mysql.getOne(sql, val)
    if packages_data:
        return packages_data
    else:
        return None


def select_yaml_lastdata():
    """
    Query the last data
    """
    mysql = Mysql()
    sql = "SELECT package_id FROM cve_git_open_euler order by git_id desc"
    package_ids = mysql.getOne(sql)
    if package_ids and len(package_ids) > 0:
        return package_ids
    else:
        return None


def store_yaml_data(yaml_data):
    """
    parse dict
    Store yaml data to mysql
    return None
    """
    mysql = Mysql()
    if yaml_data is not None and len(yaml_data) > 0:
        # Delete all data before updating
        update_yaml_origin_mark(mysql)
        for repo_key, repo_value in yaml_data.items():
            try:
                for yaml_key, yaml_value in repo_value.items():
                    if "version" not in yaml_value or not yaml_value["version"]:
                        yaml_value["version"] = ""
                    origin_data = select_yaml_origin_data(yaml_key, yaml_value["version"], mysql, repo_key)
                    if origin_data:
                        update_yaml_origin_data(origin_data["id"], yaml_value, mysql)
                    else:
                        insert_yaml_origin_data(yaml_key, yaml_value, mysql, repo_key)
                    packages_data = select_yaml_data(yaml_key, yaml_value, mysql)
                    if packages_data is not None:
                        if len(packages_data) > 1:
                            for pd in packages_data[1:]:
                                delete_yaml_openeuler_detail_data(mysql, pd["git_id"])
                                delete_yaml_openeuler_data(mysql, pd["git_id"])
                        pk = packages_data[0]
                        update_yaml_data(pk["package_id"], yaml_key, yaml_value, mysql)
                        update_yaml_detail_data(pk["git_id"], yaml_key, yaml_value, mysql)
                    else:
                        package_ids = select_yaml_lastdata()
                        if package_ids is not None and package_ids["package_id"] >= 10000000:
                            packg_id = add_package_id(package_ids["package_id"])
                        else:
                            packg_id = add_package_id(0)
                        last_id = insert_yaml_data(packg_id, yaml_key, yaml_value, mysql)
                        insert_yaml_detail_data(last_id, yaml_key, yaml_value, mysql)
                    mysql.dispose()
            except pymysql.err.IntegrityError:
                print(pymysql.err.IntegrityError)
                # except Exception as e:
                #     print(e)
                mysql.dispose(2)
        delete_yaml_origin_mark(mysql)
    mysql.close()


def proc_mindspore_yaml():
    """
    1. Create a folder;
    2. Download yaml;
    3. Parse yaml;
    4. Save in mysql;
    return None
    """
    file_name = download_mindspore_yaml()
    if files.file_isexists(file_name):
        yaml_data = files.parse_yaml(file_name)
        if yaml_data is not None and len(yaml_data) > 0:
            store_yaml_data(yaml_data)
    else:
        print("File download failed, file: ", file_name)
    # delete history yaml_data
    common.delete_yaml_data()
